using System.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using UnityEngine;

public class PhysicsCheck : MonoBehaviour
{
    private CapsuleCollider2D coll;
    private PlayerController playerController;
    private Rigidbody2D rb;

    [Header("状态")]
    public bool manual;
    public bool isGround;
    public bool isJump;
    public bool touchleftWall;
    public bool touchrightWall;
    [Header("检测参数")]
    public LayerMask groundLayer;
    public float checkRadius;
    public Vector2 bottomOffset;
    public Vector2 leftOffset;
    public Vector2 rightOffset;
    public int maxJumpnumbers;
    public int currentJumpnumbers;

    [Header("物理材质")]
    public PhysicsMaterial2D normal,smooth;

    private void Awake()
    {
        coll = GetComponent<CapsuleCollider2D>();
        playerController = GetComponent<PlayerController>();
        rb = GetComponent<Rigidbody2D>();

        if (!manual)
        {
            leftOffset = new Vector2(coll.offset.x - coll.bounds.size.x / 2, coll.bounds.size.y / 2);
            rightOffset = new Vector2(coll.offset.x + coll.bounds.size.x / 2, coll.bounds.size.y / 2);
        }

        isJump = false;
    }

    private void Update()
    {
        Check();
        JumpCheck();
        UpdatePhysicsMaterial();

    }

    private void Check() 
    {
        //检测地面
        isGround = Physics2D.OverlapCircle((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x,bottomOffset.y), checkRadius, groundLayer);

        //检测墙壁
        touchleftWall = Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, checkRadius,groundLayer);
        touchrightWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, checkRadius, groundLayer);

    }

    private void JumpCheck()
    {
        if(!isGround)
            isJump = true;

        if(isGround && isJump)
        {
            currentJumpnumbers = maxJumpnumbers;
            isJump = false;
        }

    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.DrawWireSphere((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x, bottomOffset.y), checkRadius);
        Gizmos.DrawWireSphere((Vector2)transform.position + leftOffset, checkRadius);
        Gizmos.DrawWireSphere((Vector2)transform.position + rightOffset, checkRadius);
    }

    private void UpdatePhysicsMaterial()
    {
        if(!isGround || playerController.isDash)
            rb.sharedMaterial = smooth;
        else
            rb.sharedMaterial = normal;

    }
}
